package com.osce.web.controller.system;

import com.osce.common.annotation.Log;
import com.osce.common.constant.UserConstants;
import com.osce.common.core.controller.BaseController;
import com.osce.common.core.entity.AjaxResult;
import com.osce.common.core.entity.entity.SysUser;
import com.osce.common.core.entity.vo.StudentExcelVo;
import com.osce.common.core.page.TableDataInfo;
import com.osce.common.enums.BusinessType;
import com.osce.common.utils.SecurityUtils;
import com.osce.common.utils.StringUtils;
import com.osce.common.utils.poi.ExcelUtil;
import com.osce.interfaces.system.IStudentService;
import com.osce.interfaces.system.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 学生信息
 *
 * @author doudou
 */
@RestController
@RequestMapping("/system/student")
public class StudentController extends BaseController {

    @Autowired
    private IStudentService studentService;

    @Autowired
    private ISysUserService userService;


    /**
     * 获取学生列表
     */
    @PreAuthorize("@ss.hasPermi('system:student:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        user.setUserType(UserConstants.STUDENT_TYPE);
        startPage();
        List<SysUser> list = studentService.selectList(user);
        return getDataTable(list);
    }

    /**
     * 平板端获取组织下学生列表
     */
    @GetMapping("/slab_list/{deptId}")
    public AjaxResult slab_list(@PathVariable("deptId") Long deptId) {
        List<SysUser> list = studentService.selectSlabList(deptId);
        return AjaxResult.success(list);
    }

    /**
     * 新增学生
     */
    @PreAuthorize("@ss.hasPermi('system:student:add')")
    @Log(title = "学生管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增学生'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增学生'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增学生'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUserType(UserConstants.STUDENT_TYPE);
        user.setRoleIds(UserConstants.STUDENT_ROLES);
        return toAjax(userService.insertUser(user));
    }

    /**
     * 导出模板
     */
    @PostMapping("/importTemplate")
    @PreAuthorize("@ss.hasPermi('system:student:import')")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<StudentExcelVo> util = new ExcelUtil<>(StudentExcelVo.class);
        util.importTemplateExcel(response, "学生数据");
    }

    @Log(title = "导出学生列表", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:student:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user, String exportFields, String encryptFields) {
        user.setUserType(UserConstants.STUDENT_TYPE);
        List<SysUser> list = studentService.selectList(user);
        List<StudentExcelVo> userList = studentService.toExcelVo(list);
        ExcelUtil<StudentExcelVo> util = new ExcelUtil<>(StudentExcelVo.class);

        // 处理加密字段
        if (StringUtils.isNotEmpty(encryptFields)) {
            String[] fields = encryptFields.split(",");
            for (String field : fields) {
                util.encryptColumn(field);
            }
        }

        // 如果指定了导出字段，计算需要排除的字段
        if (StringUtils.isNotEmpty(exportFields)) {
            Set<String> selectedFields = new HashSet<>(Arrays.asList(exportFields.split(",")));
            List<String> allExportableFields = new ArrayList<>();

            // 所有有@Excel注解的字段都是可导出的
            allExportableFields.add("userName"); // 登录账户
            allExportableFields.add("nickName"); // 学生姓名
            allExportableFields.add("email"); // 邮箱
            allExportableFields.add("identity"); // 身份证
            allExportableFields.add("phonenumber"); // 手机号码
            allExportableFields.add("birthday"); // 生日
            allExportableFields.add("sex"); // 用户性别
            allExportableFields.add("deptName"); // 所属科室
            allExportableFields.add("school"); // 学校
            allExportableFields.add("base"); // 学科
            allExportableFields.add("post"); // 职称
            // 军人表相关字段
            allExportableFields.add("nation"); // 民族
            allExportableFields.add("nativePlace"); // 籍贯
            allExportableFields.add("enlistmentTime"); // 入伍时间
            allExportableFields.add("partyJoiningTime"); // 入党时间
            allExportableFields.add("enlistmentPlace"); // 入伍地
            allExportableFields.add("educationDegreeId"); // 学历学位
            allExportableFields.add("bloodType"); // 血型
            allExportableFields.add("personnelCategoryId"); // 人员类别
            allExportableFields.add("securityCardNo"); // 保障卡号
            allExportableFields.add("militaryIdNo"); // 军人证件号
            allExportableFields.add("organizationalCategory"); // 总支
            allExportableFields.add("dutyTitle"); // 部职别

            // 计算需要排除的字段（不在selectedFields中的字段）
            List<String> excludeFields = new ArrayList<>();
            for (String field : allExportableFields) {
                if (!selectedFields.contains(field)) {
                    excludeFields.add(field);
                }
            }

            // 调用hideColumn方法排除不需要的字段
            if (!excludeFields.isEmpty()) {
                util.hideColumn(excludeFields.toArray(new String[0]));
            }
        }

        util.exportExcel(response, userList, "学生数据");
    }

    /**
     * 导入学生
     */
    @Log(title = "导入学生", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:student:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<StudentExcelVo> util = new ExcelUtil<>(StudentExcelVo.class);
        List<StudentExcelVo> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = studentService.importStudent(userList, updateSupport, operName);
        return success(message);
    }
}
